package com.yc.http.v1.impl;

import com.yc.http.v1.*;

import javax.servlet.annotation.WebServlet;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/cookie.s")
public class CookieServlet extends HttpServletImpl {
    /**
     * cookie : 浏览器端保存少量数据的技术
     *  少量: 4K 50个数据项
     *  存储位置: 1. 没有有效期=>内存, 2. 有有效期=>硬盘=>临时文件
     *  属性: name, value, path, domain...
     *  特点: 浏览器默认每次发送请求时, 都会带上cookie数据, 返回给服务器
     *        服务器也可以主动推送 cookie
     */

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        response.setContentType("text/html;charset=utf-8");
        final PrintWriter out = response.getWriter();
        final Cookie[] cookies = request.getCookies();
        if(cookies!=null){
            for (Cookie cookie : cookies) {
               out.append("<li>")
                       .append(cookie.getName())
                       .append(" = ")
                       .append(cookie.getValue())
                       .append("</li>");
            }
        }

        // 添加cookie
        final String add = request.getParameter("add");
        // 移除cookie
        final String del = request.getParameter("del");

        Cookie cookie1 = new CookieImpl("add", add); // TODO 添加
        Cookie cookie2 = new CookieImpl(del, null); // TODO 删除
        cookie2.setMaxAge(0);  // 0 秒, 有效期

        response.addCookie(cookie1);
        response.addCookie(cookie2);

    }
}
